/*
 * Copyright (c) 2011 Norbert Kopcsek
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.modulr.framework {

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;

	import org.modulr.bundle.Bundle;
	import org.modulr.bundle.BundleContext;
	import org.modulr.bundle.BundleRegistry;
	import org.modulr.bundle.IBundleContext;
	import org.modulr.bundle.IBundleListener;
	import org.modulr.feature.Feature;
	import org.modulr.feature.FeatureEvent;
	import org.modulr.feature.FeatureRegistry;
	import org.modulr.service.IServiceListener;
	import org.modulr.service.ServiceEvent;
	import org.modulr.service.ServiceRegistry;

	[DefaultProperty( "source" )]
	[Event( name="complete", type="flash.events.Event" )]
	[Event( name="registered", type="org.modulr.service.ServiceEvent" )]
	[Event( name="unregistered", type="org.modulr.service.ServiceEvent" )]
	[Event( name="unregistering", type="org.modulr.service.ServiceEvent" )]
	[Event( name="error", type="org.modulr.framework.FrameworkEvent" )]
	[Event( name="installationComplete", type="org.modulr.framework.FrameworkEvent" )]
	/**
	 * The core class of the Modulr framework.
	 * Maintains the central feature, bundle and service registry.
	 *
	 * @author Norbert Kopcsek
	 */
	public class Framework extends EventDispatcher {


		//------------------------------------------------------------------------------
		//
		//   Constructor 
		//
		//------------------------------------------------------------------------------

		public function Framework() {
			_serviceRegistry = new ServiceRegistry( this );
			_serviceRegistry.addEventListener( ServiceEvent.SERVICE_REGISTERED, serviceRegistry_eventHandler );
			_serviceRegistry.addEventListener( ServiceEvent.SERVICE_UNREGISTERED, serviceRegistry_eventHandler );
			_serviceRegistry.addEventListener( ServiceEvent.SERVICE_UNREGISTERING, serviceRegistry_eventHandler );

			_bundleRegistry = new BundleRegistry( this );
			_bundleRegistry.addEventListener( Event.COMPLETE, bundleRegistry_completeHandler ); // no weak reference

			_featureRegistry = new FeatureRegistry( this );
			_featureRegistry.addEventListener( FeatureEvent.FEATURE_LOADED, featureRegistry_featureLoadedHandler );
		}


		//------------------------------------------------------------------------------
		//
		//   Properties (Getter/Setter) 
		//
		//------------------------------------------------------------------------------

		//--------------------------------------
		// bundleUrls 
		//--------------------------------------

		/**
		 * Comma separated list of bundle urls.
		 * Put "bundle.xml" to load a single bundle descriptor file from application directory.
		 */
		public function get bundleUrls():String {
			return _bundleUrls
		}

		public function set bundleUrls( value:String ):void {
			_bundleUrls = value;

			var bundleUrlList:Array = value.split( "," );

			for each ( var bundleUrl:String in bundleUrlList ) {
				loadBundlesXml( new URLRequest( bundleUrl ));
			}
		}

		//--------------------------------------
		// featureUrls 
		//--------------------------------------

		/**
		 * Comma separated list of feature urls.
		 * Put "feature.xml" to load a single feature descriptor file from application directory.
		 */
		public function get featureUrls():String {
			return _featureUrls
		}

		public function set featureUrls( value:String ):void {
			_featureUrls = value;

			var featureUrlList:Array = value.split( "," );

			for each ( var featureUrl:String in featureUrlList ) {
				loadFeaturesXml( new URLRequest( featureUrl ));
			}
		}

		//--------------------------------------
		// featureRegistry 
		//--------------------------------------

		/**
		 * Returns the bundle registry registered at the framework.
		 *
		 * Read only.
		 * return The bundle registry registered at the framework.
		 */
		public function get featureRegistry():FeatureRegistry {
			return _featureRegistry
		}

		//--------------------------------------
		// bundleRegistry 
		//--------------------------------------

		/**
		 * Returns the bundle registry registered at the framework.
		 *
		 * Read only.
		 * return The bundle registry registered at the framework.
		 */
		public function get bundleRegistry():BundleRegistry {
			return _bundleRegistry
		}

		//--------------------------------------
		// serviceRegistry 
		//--------------------------------------

		/**
		 * Returns the bundle registry registered at the framework.
		 *
		 * Read only.
		 * return The bundle registry registered at the framework.
		 */
		public function get serviceRegistry():ServiceRegistry {
			return _serviceRegistry
		}

		//--------------------------------------
		// applicationContext 
		//--------------------------------------

		public function get applicationContext():IBundleContext {
			if ( _applicationContext == null ) {
				var applicationBundle:Bundle = new Bundle( "application", "application" );
				_applicationContext = new BundleContext( this, applicationBundle );
			}
			return _applicationContext;
		}

		//--------------------------------------
		// domain 
		//--------------------------------------

		/**
		 * The application domain all bundles are loaded to.
		 *
		 * return The appliction domain used for loading bundles.
		 */
		public function get domain():ApplicationDomain {
			return _domain;
		}

		public function set domain( value:ApplicationDomain ):void {
			_domain = value;

			trace( "Framework domain set to " + value );
		}

		//--------------------------------------
		// source 
		//--------------------------------------

		public function set source( value:Array ):void {
			for each ( var object:Object in value ) {
				if ( object is Bundle ) {
					bundleRegistry.installBundle( object as Bundle );
				} else if ( object is Feature ) {
					featureRegistry.installFeature( object as Feature );
				}
			}

			dispatchEvent( new FrameworkEvent( FrameworkEvent.INSTALLATION_COMPLETE ));

			// TODO: Move to bundleRegistry ...
			bundleRegistry.loadMandatoryBundles();
		}


		//------------------------------------------------------------------------------
		//
		//   Protected fields 
		//
		//------------------------------------------------------------------------------

		/**
		 * @private
		 */
		private var _domain:ApplicationDomain;

		/**
		 * @private
		 */
		private var _bundleUrls:String;

		/**
		 * @private
		 */
		private var _featureUrls:String;

		/**
		 * @private
		 */
		private var _featureRegistry:FeatureRegistry;

		/**
		 * @private
		 */
		private var _bundleRegistry:BundleRegistry;

		/**
		 * @private
		 */
		private var _serviceRegistry:ServiceRegistry;

		/**
		 * @private
		 */
		private var _applicationContext:IBundleContext;


		//------------------------------------------------------------------------------
		//
		//  Methods 
		//
		//------------------------------------------------------------------------------

		/**
		 * Loads a bundle.xml and registers all bundles.
		 * @param urlRequest The URLRequest to the bundle.xml.
		 */
		public function loadBundlesXml( urlRequest:URLRequest ):void {
			_bundleRegistry.loadBundlesXml( urlRequest );
		}

		/**
		 * Loads a features.xml, registers all features and loads all mandatory bundles.
		 * @param urlRequest The URLRequest to the features.xml.
		 */
		public function loadFeaturesXml( urlRequest:URLRequest ):void {
			_featureRegistry.loadFeaturesXml( urlRequest );
		}

		/**
		 * Returns the bundle for the given id.
		 * @param id The id of the bundle to be loaded.
		 * @return The bundle returned by the framework.
		 */
		public function getBundleById( id:String ):Bundle {
			return _bundleRegistry.getBundleById( id );
		}

		/**
		 * Activates the given bundle.
		 * @param bundle The bundle to be activated.
		 */
		public function activateBundle( bundle:Bundle ):void {
			if ( bundle == null ) // this or error
			{
				return;
			}
			_bundleRegistry.loadBundle( bundle );
		}

		/**
		 * Passivates the given bundle.
		 * @param bundle The bundle to be passivated.
		 */
		public function passivateBundleById( bundle:Bundle ):void {
			_bundleRegistry.unloadBundle( bundle );
		}

		/**
		 * Adds the specified IBundleListener object to the context bundle's list of listeners.
		 */
		public function addBundleListener( listener:IBundleListener ):void {
			bundleRegistry.addBundleListener( listener );
		}

		/**
		 * Removes the specified IBundleListener object from the context bundle's list of listeners.
		 */
		public function removeBundleListener( listener:IBundleListener ):void {
			bundleRegistry.removeBundleListener( listener );
		}

		/**
		 * Adds the specified IServiceListener object to the context bundle's list of listeners.
		 */
		public function addServiceListener( listener:IServiceListener ):void {
			addEventListener( ServiceEvent.SERVICE_REGISTERED, listener.serviceRegisteredHandler );
			addEventListener( ServiceEvent.SERVICE_UNREGISTERED, listener.serviceUnregisteredHandler );
			addEventListener( ServiceEvent.SERVICE_UNREGISTERING, listener.serviceUnregisteringHandler );
		}

		/**
		 * Removes the specified IServiceListener object from the context bundle's list of listeners.
		 */
		public function removeServiceListener( listener:IServiceListener ):void {
			removeEventListener( ServiceEvent.SERVICE_REGISTERED, listener.serviceRegisteredHandler );
			removeEventListener( ServiceEvent.SERVICE_UNREGISTERED, listener.serviceUnregisteredHandler );
			removeEventListener( ServiceEvent.SERVICE_UNREGISTERING, listener.serviceUnregisteringHandler );
		}


		//------------------------------------------------------------------------------
		//
		//   Protected methods 
		//
		//------------------------------------------------------------------------------

		/**
		 * @private
		 */
		protected function serviceRegistry_eventHandler( event:Event ):void {
			dispatchEvent( event );
		}

		/**
		 * @private
		 */
		protected function bundleRegistry_completeHandler( event:Event ):void {
			dispatchEvent( event );
		}

		/**
		 * @private
		 */
		protected function featureRegistry_featureLoadedHandler( event:FeatureEvent ):void {
			bundleRegistry.installBundlesFromXml( event.feature.bundlesXml );
			bundleRegistry.loadMandatoryBundles();
			dispatchEvent( event );
		}
	}
}

